<style lang="less">
@import "./main3.less";
</style>
<template>
    <div class="main" :class="{'main-hide-text': shrink}">
        <!-- <div class="sidebar-menu-con" :style="{width: shrink?'60px':'200px', overflow: shrink ? 'visible' : 'auto'}">
            <shrinkable-menu :shrink="shrink" @on-change="handleSubmenuChange" :theme="menuTheme" :before-push="beforePush" :open-names="openedSubmenuArr" :menu-list="menuList">
                <div slot="top" class="logo-con" >
                <div>
                    <img v-show="!shrink" src="../images/logo.jpg" key="max-logo" >
                    <img v-show="shrink" src="../images/logo-min.jpg" key="min-logo" >
                </div>
                </div>
            </shrinkable-menu>
        </div> -->
        <!-- <div class="main-header-con" :style="{paddingLeft: shrink?'60px':'200px'}" > -->
        <div class="main-header-con" style="paddingLeft:0">
            <div class="main-header">
                <!-- <div class="navicon-con">
                    <Button :style="{transform: 'rotateZ(' + (this.shrink ? '-90' : '0') + 'deg)'}" type="text" @click="toggleClick" >
                        <Icon type="md-menu" size="32" ></Icon>
                    </Button>
                </div> -->
                <!-- <div class="header-middle-con">
                    <div class="main-breadcrumb">
                        <breadcrumb-nav :currentPath="currentPath"></breadcrumb-nav>
                    </div>
                </div> -->
                <div class="header-left-con ml-10">
                    <Tabs type="card" @on-click="clickTab" v-model="currentTabIndex">
                        <TabPane :icon="item.icon" :label="item.name" v-for="item in menuArr" :key="item.id"></TabPane>
                    </Tabs>
                </div>
                <div class="header-avator-con">
                    <Tooltip content="系统设置" v-if="userType == 2"><Icon type="md-construct" size="20" @click="goToSettings"/></Tooltip>
                    <full-screen v-model="isFullScreen" @on-change="fullscreenChange" ></full-screen>
                    <lock-screen></lock-screen>
                    <message-tip v-model="mesCount"></message-tip>
                    <!-- <theme-switch></theme-switch> -->
                    <div class="user-dropdown-menu-con">
                        <Row  type="flex" justify="end" align="middle" class="user-dropdown-innercon" >
                            <Dropdown transfer trigger="click" @on-click="handleClickUserDropdown" >
                                <div style="color: #2d8cf0;text-align: center;">
                                    <p v-if="company.companyName != null && company.companyName.length <= 10">{{ company.companyName }}</p>
                                    <p v-else-if="company.companyName != null && company.companyName.length > 10">{{ company.companyName.substring(0, 10) + "..." }}</p>
                                    <p class="main-user-name">
                                        <!-- 武汉大念投资管理有限公司<br /> -->
                                        {{ userName }}
                                    </p>
                                    <Icon type="md-arrow-dropdown"></Icon>
                                </div>
                                <DropdownMenu slot="list">
                                    <DropdownItem name="ownSpace">个人中心</DropdownItem>
                                    <DropdownItem  name="modifiPassword" divided >修改密码</DropdownItem>
                                    <DropdownItem name="modifiPhone" divided >修改手机号</DropdownItem>
                                    <DropdownItem name="switchingEnterprises" divided v-if="changeCompany.companyList != null && changeCompany.companyList.length > 0">切换企业</DropdownItem>
                                    <DropdownItem name="loginout" divided >退出登录</DropdownItem>
                                </DropdownMenu>
                            </Dropdown>
                            <Avatar :src="avatorPath" style="background: #619fe7;margin-left: 10px;" ></Avatar>
                        </Row>
                    </div>
                </div>
            </div>
            <div class="tags-con" v-if="menuArr.length > 0 && menuArr.length > currentTabIndex">
                <tags-page-opened :pageTagsList="menuArr[currentTabIndex].children" :selectedTab="menuArr[currentTabIndex].selectedTab" @selectTag="clickSubTab"></tags-page-opened>
                <!-- :waitArr="waitArr" -->
            </div>
        </div>
        <div class="single-page-con" style="left: 0" >
        <!-- <div class="single-page-con" :style="{left: shrink?'60px':'200px'}" > -->
            <div class="single-page">
                <keep-alive :include="cachePage">
                    <router-view></router-view>
                </keep-alive>
            </div>
        </div>
        <!-- 自定义模态框 -->
        <Modal  v-model="modifi.Modal" title="修改密码" :mask-closable="false" :draggable="true">
            <Form :model="modifi.form" :label-width="70" ref="modifiForm" :rules="modifi.ruleValidate" >
                <!-- ref == id rules:表单验证 -->
                <FormItem label="原始密码" prop="oldPwd" >
                <Input v-model="modifi.form.oldPwd" placeholder="请输入原始密码" type="password"/>
                </FormItem>
                <FormItem label="新密码" prop="newPwd" >
                <Input v-model="modifi.form.newPwd" type="password"/>
                </FormItem>
                <FormItem label="确认密码" prop="Pwd" >
                <Input v-model="modifi.form.Pwd" type="password"/>
                </FormItem>
            </Form>
            <div slot="footer">
                <Row type="flex" justify="center" class="code-row-bg" >
                    <Col span="5">
                        <Button type="primary"  @click="deleteForm('modifiForm')" >取消</Button>
                    </Col>
                    <Col span="5">
                        <Button type="primary"  @click="saveModifi('modifiForm')" >确认修改</Button>
                        <!-- modifiForm == id == ref -->
                    </Col>
                </Row>
            </div>
        </Modal>
        <Modal v-model="phoneDifi.Modal" title="修改手机号" :mask-closable="false" :draggable="true">
            <Form :model="phoneDifi.form" :label-width="70" ref="phoneForm" :rules="phoneDifi.ruleValidatephone" >
                <FormItem label="手机号" prop="phone" >
                    <Input v-model="phone" disabled />
                </FormItem>
                <FormItem label="密码"  prop="phonePwd" >
                    <Input v-model="phoneDifi.form.phonePwd" placeholder="请输入密码" type="password" />
                </FormItem>
                <FormItem label="新手机号" prop="newPhone" >
                    <Input v-model="phoneDifi.form.newPhone" placeholder="请输入新手机号" />
                </FormItem>
                <FormItem label="验证码" prop="verificationCode" class="verificationCode-class">
                    <Input v-model="phoneDifi.form.verificationCode" placeholder="请输入收到的短信验证码" />
                        <!-- 验证码 -->
                    <img style="display: block" :src="verificationCodeImg" alt=""  @click='goVc()'  class="noBorder">
                </FormItem>
            </Form>
            <div slot="footer">
                <Row type="flex" justify="center" class="code-row-bg" >
                <Col span="5">
                <Button type="primary" @click="deleteForm('phoneForm')">取消</Button>
                </Col>
                <Col span="5">
                <Button
                    type="primary"
                    @click="saveModifi('phoneForm')"
                >确认修改</Button>
                </Col>
                </Row>
            </div>
        </Modal>
        <Modal  :draggable="true" v-model="changeCompany.modal" title="切换公司" :mask-closable="false" :footer-hide="true">
            <Table :columns="changeCompany.columns" :data="changeCompany.companyList" @on-row-click="chooseCompany"></Table>
        </modal>
    </div>
</template>
<script>
import shrinkableMenu from './main-components/shrinkable-menu/shrinkable-menu.vue';
import tagsPageOpened from './main-components/tags-page-opened.vue';
import breadcrumbNav from './main-components/breadcrumb-nav.vue';
import fullScreen from './main-components/fullscreen.vue';
import lockScreen from './main-components/lockscreen/lockscreen.vue';
import messageTip from './main-components/message-tip.vue';
import themeSwitch from './main-components/theme-switch/theme-switch.vue';
import Cookies from 'js-cookie';
import util from '@/libs/util.js';

export default {
    components: {
        shrinkableMenu,
        tagsPageOpened,
        breadcrumbNav,
        fullScreen,
        lockScreen,
        messageTip,
        themeSwitch
    },
    data () {
        // 新密码验证
        const validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('此项为必填项'));
            } else {
                var passReg = /^[a-zA-Z0-9\u4e00-\u9fa5_]*$/;
                if (!passReg.test(value)) {
                    callback(new Error('格式有误'));
                } else {
                    callback();
                }
            }
        };
        const validatePassAgin = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('此项为必填项'));
            } else {
                var passReg = /^[a-zA-Z0-9\u4e00-\u9fa5_]*$/;
                if (!passReg.test(value)) {
                    callback(new Error('格式有误，请重新输入'));
                } else if (value !== this.modifi.form.newPwd) {
                    callback(new Error('两次密码输入不相等，请重新输入'));
                } else {
                    callback();
                }
            }
        };
        return {
            // 公司信息
            company: {
                id: null,
                companyName: null
            },
            shrink: true,
            userName: '',
            password: '',
            isFullScreen: false,
            openedSubmenuArr: this.$store.state.app.openedSubmenuArr,
            Cookies: Cookies,
            // 获取手机号
            phone: '',
            // 是否弹出修改密码框
            verificationCodeImg: '',
            modifi: {
                Modal: false,
                // 动态标题
                // title: '',
                form: {
                    oldPwd: '',
                    newPwd: '',
                    Pwd: ''
                },
                // 获取的手机号
                //  修改密码
                ruleValidate: {
                    loading: false,
                    oldPwd: [
                        {
                            required: true,
                            type: 'string',
                            message: '原始密码输入有误',
                            trigger: 'blur'
                        },
                        {
                            type: 'string',
                            pattern: /^[a-zA-Z0-9\u4e00-\u9fa5_]*$/,
                            message: '描述只能输入汉字数字英文下划线',
                            trigger: 'blur'
                        }
                    ],
                    newPwd: { validator: validatePass, trigger: 'blur', required: true },
                    Pwd: [
                        { validator: validatePassAgin, trigger: 'blur' }

                    ]
                }
            },
            //   手机验证
            phoneDifi: {
                Modal: false,
                form: {
                    phonePwd: '',
                    newPhone: '',
                    verificationCode: ''
                },
                ruleValidatephone: {
                    loading: false,
                    phonePwd: [
                        {
                            required: true,
                            type: 'string',
                            message: '原始密码输入有误',
                            trigger: 'blur'
                        },
                        {
                            type: 'string',
                            pattern: /^[a-zA-Z0-9\u4e00-\u9fa5_]*$/,
                            message: '描述只能输入汉字数字英文下划线',
                            trigger: 'blur'
                        }
                    ],

                    newPhone: [
                        {
                            required: true,
                            type: 'string',
                            message: '手机号码输入有误',
                            trigger: 'blur'
                        },
                        {
                            type: 'string',
                            pattern: /^1\d{10}$/,
                            message: '手机号输入不正确,请重新输入',
                            trigger: 'blur'
                        }
                    ],
                    verificationCode: [
                        {
                            required: true,
                            type: 'string',
                            message: '验证码输入有误',
                            trigger: 'blur'
                        },
                        {
                            type: 'string',
                            pattern: /^[0-9]*$/,
                            message: '验证码输入有误',
                            trigger: 'blur'
                        }
                    ]
                }
            },
            changeCompany: {
                // 是否打开窗口
                modal: false,
                columns: [
                    {
                        title: '公司名称',
                        key: 'companyName',
                        align: 'center'
                    }
                ],
                // 数据
                companyList: []
            },
            menuArr: [],
            // waitArr: [],
            currentTabIndex: '',
            oldName: '',
            waitName: '',
            userType: null
        };
    },
    computed: {
        menuList () {
            return this.$store.state.app.menuList;
        },
        pageTagsList: {
            get: function () {
                let arr = JSON.parse(JSON.stringify(this.$store.state.app.pageOpenedList));
                console.log(arr, '进来了1');
                return this.$store.state.app.pageOpenedList;
            },
            set: function (newValue) {
                console.log(newValue, '995');
                localStorage.pageOpenedList = JSON.stringify(newValue);
                return newValue;
            }
        },
        currentPath () {
            return this.$store.state.app.currentPath; // 当前面包屑数组
        },
        avatorPath () {
            return localStorage.avatorImgPath;
        },
        cachePage () {
            return this.$store.state.app.cachePage;
        },
        lang () {
            return this.$store.state.app.lang;
        },
        menuTheme () {
            return this.$store.state.app.menuTheme;
        },
        mesCount () {
            return this.$store.state.app.messageCount;
        }
    },
    methods: {
        chooseCompany (param, index) {
            if (param && param.id) {
                depot.post({
                    url: this.URL.USER.CHANGE_COMPANY,
                    data: param.id,
                    cb: data => {
                        if (data.code === 0) {
                            let company = {
                                id: param.id,
                                companyName: param.companyName
                            };
                            this.$store.commit('clearAllTags');
                            this.$router.push({
                                name: 'home_index'
                            });
                            localStorage.setItem('company', JSON.stringify(company));
                            location.reload();
                        } else {
                            this.$Message.error(data.message);
                        }
                    }
                });
            }
        },
        init () {
            // let pathArr = util.setCurrentPath(this, this.$route.name);
            // this.$store.commit('updateMenulist');
            // if (pathArr.length >= 2) {
            //     this.$store.commit('addOpenSubmenu', pathArr[1].name);
            // }
            this.userName = Cookies.get('user');
            // 从登陆时候获取电话号码
            this.phone = Cookies.get('phone');
            // console.log(this.phone, 'this.phonethis');
            // this.checkTag(this.$route.name);

            this.getCountByMessageLogNotRead();

            this.getMenu();
        },
        // 拿Menu
        getMenu () {
            let menusCache = localStorage.getItem('menus');
            if (menusCache) {
                this.menuArr = JSON.parse(menusCache);
                let currentTabIndex = localStorage.getItem('currentTabIndex');
                if (currentTabIndex === null || currentTabIndex === undefined) {
                    this.currentTabIndex = 0;
                } else {
                    this.currentTabIndex = parseInt(currentTabIndex);
                }
            } else {
                depot.get({
                    url: this.URL.USER.MENUS,
                    cb: (data) => {
                        let num = localStorage.getItem('currentTabIndex');
                        if (!+num) {
                            this.currentTabIndex = 0;
                        } else {
                            data.data.forEach((item, index) => {
                                if (+num === index) {
                                    this.currentTabIndex = index;
                                }
                            });
                        }
                        this.menuArr.splice(0, this.menuArr.length);
                        this.menuArr = data.data;
                        this.menuArr.forEach((menu, index) => {
                            menu.selectedTab = 0;
                        });
                        localStorage.setItem('menus', JSON.stringify(this.menuArr));
                        localStorage.setItem('currentTabIndex', 0);
                    }
                });
            }
        },
        // 点击当前tab
        clickTab (val) {
            localStorage.setItem('currentTabIndex', val);
            localStorage.setItem('menus', JSON.stringify(this.menuArr));
            this.currentTabIndex = val;
            this.menuArr[this.currentTabIndex].selectedTab = 0;
            this.$router.push({
                name: this.menuArr[this.currentTabIndex].children[0].link
            });
        },

        // 拿到消息中心未读信息个数并放入store
        getCountByMessageLogNotRead () {
            this.showSpin = true;
            depot.get({
                url: this.URL.MESSAGE.COUNT_BY_MESSAGELOG_NOT_READ,
                cb: (data) => {
                    this.showSpin = false;
                    if (data.code === 0) {
                        let messageCount = data.data;
                        this.$store.commit('setMessageCount', messageCount);
                    } else if (data.code === 999) {
                        this.$Message.error(data.message);
                    }
                },
                ce: (error) => {
                    this.showSpin = false;
                }
            });
        },
        toggleClick () {
            this.shrink = !this.shrink;
        },
        handleClickUserDropdown (name) {
            if (name === 'ownSpace') {
                // util.openNewPage(this, 'ownspace_index');
                // this.$router.push({
                //     name: 'ownspace_index'
                // });
                // util.openNewPage(this, 'ownspace_index');
                this.$router.push({
                    name: 'ownspace_index'
                });
            } else if (name === 'loginout') {
                this.loginOut();
            } else if (name === 'modifiPassword') {
                // 打开修改密码的弹窗
                this.modifi.Modal = true;
                // 1.执行清空表单操作
                this.$refs.modifiForm.resetFields();
                // this.saveModifi();
            } else if (name === 'modifiPhone') {
                // 打开修改手机号的弹窗
                this.phoneDifi.Modal = true;
                // 1.执行清空表单操作
                this.$refs.phoneForm.resetFields();
                //   this.savePhoneModel();
            } else if (name === 'switchingEnterprises') {
                this.changeCompany.modal = true;
            }
        },
        // 获取公司列表
        findCompanyList () {
            depot.get({
                url: this.URL.USER.FIND_MY_COMPANY_LIST,
                cb: data => {
                    if (data.code === 0) {
                        // 排除当前公司
                        this.changeCompany.companyList = [];
                        data.data.forEach(item => {
                            if (item && item.id != this.company.id) {
                                this.changeCompany.companyList.push(item);
                            }
                        });
                    } else {
                        this.$Message.error(data.message);
                    }
                }
            });
        },
        // 登出
        loginOut () {
            depot.get({
                url: this.URL.USER.LOGOUT,
                cb: data => {
                    if (data.code === 0) {
                        // 退出登录
                        this.$store.commit('logout', this);
                        this.$store.commit('clearOpenedSubmenu');
                        this.$router.push({
                            name: 'login'
                        });
                    } else {
                        this.$Message.error(data.message);
                    }
                }
            });
        },
        checkTag (name) {
            let openpageHasTag = this.pageTagsList.some(item => {
                if (item.name === name) {
                    return true;
                }
            });
            if (!openpageHasTag) {
                //  解决关闭当前标签后再点击回退按钮会退到当前页时没有标签的问题
                // util.openNewPage(
                //     this,
                //     name,
                //     this.$route.params || {},
                //     this.$route.query || {}
                // );
            }
        },
        handleSubmenuChange (val) {},
        beforePush (name) {
            // if (name === 'accesstest_index') {
            //     return false;
            // } else {
            //     return true;
            // }
            return true;
        },
        fullscreenChange (isFullScreen) {},
        goToBusinessHome () {
            // // 跳转商家中心
            Cookies.set('access', 1);
            this.$store.commit('updateMenulist');
            this.$router.push('/home');
        },
        // 修改密码及及修改手机号
        // 1.取消修改
        deleteForm (name) {
            // 参数为修改密码得表单
            if (name == 'modifiForm') {
                // 1.关闭修改密码的弹窗
                this.modifi.Modal = false;
                // 2.执行清空表单操作
                this.$refs.modifiForm.resetFields();
            } else {
            // 参数为修改手机得表单
                // 2.关闭修改密码的弹窗
                this.phoneDifi.Modal = false;
                // 1.执行清空表单操作
                this.$refs.phoneForm.resetFields();
            }
            // // 1.执行清空表单操作
            // this.$refs.modifiForm.resetFields();
            // // 2.关闭修改密码的弹窗
            // this.modifi.Modal = false;
        },
        // 2.确认修改
        saveModifi (name) {
            console.log(name, 'names');
            // console.log(vue.password, 'password');
            // console.log(this.modifi.form.oldPwd, 'oldPwd');
            // 如果传的参数是修改密码
            if (name == 'modifiForm') {
                // 判断传入的id的表单验证
                this.$refs[name].validate(valid => {
                // ref == id; rules == 判断整个表单的所有的验证， 触发的事件中包含的是id即ref
                // 如果验证通过
                    if (valid) {
                        var passWord = {
                            oldPassword: this.modifi.form.oldPwd,
                            newPassword: this.modifi.form.newPwd,
                            repeatPassword: this.modifi.form.Pwd
                        };
                        depot.post({
                            url: this.URL.USER.UPDATE_PASSWORD,
                            data: passWord,
                            cb: data => {
                                // console.log(data, 'modifi.form');
                                if (data.code === 0) {
                                    // 成功后执行
                                    // 1.关闭修改密码的弹窗
                                    this.modifi.Modal = false;
                                    // 2.提示成功
                                    this.$Message.success('修改密码成功,请重新登陆');
                                    // 3.执行登出操作
                                    this.loginOut();
                                } else {
                                    this.$Message.error(data.message);
                                }
                            },
                            ce: error => {
                                this.$Message.error(data.message);
                            }
                        });
                    } else {
                        this.$Message.error('请按要求填写');
                    }
                });
            } else {
            // 如果传的参数是修改手机号
                var phoneArry = {
                    oldMobile: this.phone,
                    newMobile: this.phoneDifi.form.newPhone,
                    oldPassword: this.phoneDifi.form.phonePwd,
                    validateCode: this.phoneDifi.form.verificationCode
                };
                console.log(phoneArry, 'phoneArry');
                this.$refs[name].validate(valid => {
                    if (valid) {
                    // phone;
                        depot.post({
                            url: this.URL.USER.UPDATE_MOBILE_BY_IMAGE_VALIDA,
                            data: phoneArry,
                            cb: data => {
                            // console.log(data, 'modifi.form');
                                if (data.code === 0) {
                                // 成功后执行
                                // 1.关闭修改的弹窗
                                    this.phoneDifi.Modal = false;
                                    // 2.提示成功
                                    this.$Message.success('手机修改成功，请重新登陆');
                                    // 3.执行登出操作
                                    this.loginOut();
                                    console.log(data, 'data.code');
                                } else {
                                    this.$Message.error(data.message);
                                }
                            },
                            ce: (error) => {
                                this.$Message.error(data.message);
                            }
                        });
                    }
                });
            }
        },
        // 得到图形验证码
        Vc () {
            // console.log(this.phoneDifi.form.newPhone, '查看当前新输入手机号');
            var vue = this;
            // 定义得到图形验证码时需要传输的参数手机号码
            var mobile = this.phone;
            depot.get({
                url: vue.URL.DOCUMENT.GET_VERIFICATION_CODE_FOR_UPDATE_MOBILE + '?mobile=' + mobile,
                cb: data => {
                    // console.log(data, 'modifi.form');
                    if (data.code === 0) {
                        vue.verificationCodeImg = 'data:image/png;base64,' + data.data.verificationCodeImg;
                        // console.log(vue.verificationCodeImg, '查看当前验证码');
                    } else {
                        vue.$Message.error(data.message);
                    }
                },
                ce: (error) => {
                    vue.$Message.error(data.message);
                }
            });
        },
        // 点击重新得到图形验证码
        goVc () {
            this.Vc();
        },
        goToSettings () {
            window.open('/settings', '_blank');
        },
        updatePageTagsList (val) {
            this.pageTagsList = JSON.parse(JSON.stringify(val));
        },
        // 点击子菜单
        clickSubTab (val) {
            this.menuArr[this.currentTabIndex].selectedTab = val;
            localStorage.setItem('menus', JSON.stringify(this.menuArr));
            this.$router.push({
                name: this.menuArr[this.currentTabIndex].children[val].link
            });
        }
    },
    watch: {
        // $route (to) {
        //     this.$store.commit('setCurrentPageName', to.name);
        //     let pathArr = util.setCurrentPath(this, to.name);
        //     if (pathArr.length > 2) {
        //         this.$store.commit('addOpenSubmenu', pathArr[1].name);
        //     }
        //     this.checkTag(to.name);
        //     localStorage.currentPageName = to.name;
        // },
        // lang () {
        //     util.setCurrentPath(this, this.$route.name); // 在切换语言时用于刷新面包屑
        // }
        '$route' (form, to) {
            // console.log(form.name, '新', to.name, '旧');
            this.oldName = to.name;
            // console.log(this.oldName, '本地的');
            if (form.name === this.waitName) {
                // console.log(form.name, '进来了');
                this.menuArr.forEach((item, index) => {
                    if (this.currentTabIndex === index) {
                        item.children.forEach((item2, index2) => {
                            if (item2.link === form.name) {
                                // console.log(index2, '拿index2');
                                this.menuArr[this.currentTabIndex].selectedTab = index2;
                                localStorage.setItem('menus', JSON.stringify(this.menuArr));
                            }
                        });
                    }
                });
            }
        },
        'oldName' (val) {
            // console.log(this.oldName, val, 'oldName');
            this.waitName = val;
        }
    },
    created () {
        // 显示打开的页面的列表
        this.$store.commit('setOpenedList');
        let company = localStorage.getItem('company');
        if (company) {
            this.company = JSON.parse(company);
        }
        let userType = localStorage.getItem('USER_TYPE');
        if (userType) {
            this.userType = userType;
        }
        this.findCompanyList();
        this.getMenu();
    },
    mounted () {
        this.init();
        // 得到图形验证码
        this.Vc();
    }
};
</script>
